package javaAdvanced;

import java.util.Random;

/**
 * @author cuiH
 * Date: 13-10-24
 */
public class ThreadLocalTest {
    private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();  //通过源代码分析，就是map，可以查看set的方式的实现，直接set和get
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {                            //此时构造两个线程，这样就造成同一个数据域被不同线程调用时候，数据不同了
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                             int data = new Random().nextInt();
                            System.out.println(Thread.currentThread().getName() + " put data:" + data);
                            x.set(data);                    //当前线程中存书数据
                            new A().get();
                            new B().get();
                        }
                    }
            ).start();
        }
    }

    static class A {
        public void get() {
            int data = x.get();
            System.out.println("A from " + Thread.currentThread().getName() + " get data:" + data);
        }
    }

    static class B {
        public void get() {
            int data = x.get();
            System.out.println("B from " + Thread.currentThread().getName() + " get data:" + data);
        }
    }
}
/*
* 实验结果
Thread-1 put data:-1069374826
A from Thread-1 get data:-1069374826
Thread-0 put data:-162182369
A from Thread-0 get data:-162182369
B from Thread-1 get data:-1069374826
B from Thread-0 get data:-162182369
* */
